package com.example.demo.controller;

import com.example.demo.data.ResultDate;
import com.example.demo.pojo.Menu;
import com.example.demo.pojo.RoleMenu;
import com.example.demo.pojo.User;
import com.example.demo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@Transactional  //开启事务回滚
public class MenuController {

    @Autowired
    private RoleService roleService;

    //根据session获取登录的角色信息
    @GetMapping("userMenuInfo")
    public ResultDate<Object> getUserMenu(HttpServletRequest request){

        User user = (User)request.getSession().getAttribute("user");
        ResultDate<Object> resultDate = new ResultDate<>();
        if (user != null){
            //获取角色role_id
            int roleId = user.getR_id();
            List<Object> list = new ArrayList<>();
            //通过角色role_id获取中间包role_menu数据
            List<RoleMenu> roleMenus = roleService.getRoleMenuByRoleId(roleId);

            for(RoleMenu roleMenu : roleMenus) {
                //获取menu_Id
                int menuId = roleMenu.getM_id();
                //通过m_id查询menu表信息
                Menu menu = roleService.getMenuById(menuId);
                //保存菜单资源信息
                list.add(menu);
            }

            resultDate.setList(list);
        }else {
            resultDate.setStatus(-1);
            resultDate.setMsg("用户未登录！");
        }

        return resultDate;
    }

}
